package com.zg.datapush.web;

import com.zg.common.core.R;
import com.zg.datapush.req.CronDescriptionReq;
import com.zg.datapush.req.CronExpressionReq;
import com.zg.datapush.util.CronUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Map;

/**
 * Cron表达式管理Controller
 * @author zg
 */
@RestController
@RequestMapping("/datapush/cron")
@RequiredArgsConstructor
@Api(tags = "Cron表达式管理")
public class CronController {

    @ApiOperation("验证cron表达式")
    @PostMapping("/validate")
    public R<Boolean> validateCron(@RequestBody @Valid CronExpressionReq req) {
        boolean isValid = CronUtil.isValidCron(req.getCronExpression());
        return R.success(isValid);
    }

    @ApiOperation("获取常用cron表达式模板")
    @PostMapping("/templates")
    public R<Map<String, String>> getCronTemplates() {
        Map<String, String> templates = CronUtil.getCronTemplates();
        return R.success(templates);
    }

    @ApiOperation("根据描述获取cron表达式")
    @PostMapping("/getByDescription")
    public R<String> getCronByDescription(@RequestBody @Valid CronDescriptionReq req) {
        String cronExpression = CronUtil.getCronByDescription(req.getDescription());
        return R.success(cronExpression);
    }

    @ApiOperation("计算下次执行时间")
    @PostMapping("/nextTime")
    public R<Date> getNextExecuteTime(@RequestBody @Valid CronExpressionReq req) {
        Date nextTime = CronUtil.getNextExecuteTime(req.getCronExpression());
        return R.success(nextTime);
    }
}
